import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/foundation.dart';
import 'package:permission_handler/permission_handler.dart';

/// FileName permission_manager
///
/// @Author lax
/// @Date 2023/12/25
///
/// @Description

class PermissionManager {
  /// 检查权限
  static Future<bool> checkPermission({
    required List<Permission> permissionList,
    Function()? onSuccess,
    Function()? onFailed,
  }) async {
    final list = await _getDeniedPermission(
      permissionList: permissionList,
      onSuccess: onSuccess,
      onFailed: onFailed,
    );
    return list.isEmpty;
  }

  /// 返回未授权的权限
  static Future<List<Permission>> _getDeniedPermission({
    required List<Permission> permissionList,
    Function()? onSuccess,
    Function()? onFailed,
  }) async {
    final result = await _filterPermission(
      permissionList: permissionList,
      onSuccess: onSuccess,
      onFailed: onFailed,
    );
    List<Permission> newPermissionList = [];
    for (Permission permission in result) {
      // 不是允许状态就添加到新的申请列表中
      final status = await permission.status;
      if (status.isDenied ||
          status.isPermanentlyDenied ||
          status.isRestricted) {
        newPermissionList.add(permission);
      }
    }
    return newPermissionList;
  }

  /// 过滤无效权限
  static Future<List<Permission>> _filterPermission({
    required List<Permission> permissionList,
    Function()? onSuccess,
    Function()? onFailed,
  }) async {
    final asVersion = await androidSDKVersion();
    // 一个新待申请权限列表
    List<Permission> newPermissionList = [];
    // 遍历当前权限申请列表
    for (Permission permission in permissionList) {
      // 33以下没有photos videos权限，以上没有storage权限
      if (asVersion != null) {
        if (asVersion < 33) {
          if (permission == Permission.photos ||
              permission == Permission.videos) {
            continue;
          }
        } else {
          if (permission == Permission.storage) {
            continue;
          }
        }
      }
      newPermissionList.add(permission);
    }
    return newPermissionList;
  }

  /// 请求权限
  static Future<bool> requestPermission({
    required List<Permission> permissionList,
    Function()? onSuccess,
    Function()? onFailed,
    Function()? onFinish,
  }) async {
    if (kIsWeb) {
      onSuccess?.call();
      onFinish?.call();
      return true;
    }
    List<Permission> newPermissionList = await _filterPermission(
      permissionList: permissionList,
      onSuccess: onSuccess,
      onFailed: onFailed,
    );
    PermissionStatus permissionStatus =
        await _requestPermission(newPermissionList);

    switch (permissionStatus) {
      case PermissionStatus.granted:
      case PermissionStatus.limited:
      case PermissionStatus.provisional:
        {
          onSuccess?.call();
          onFinish?.call();
          return true;
        }
      case PermissionStatus.denied:
      case PermissionStatus.restricted:
      case PermissionStatus.permanentlyDenied:
        {
          onFailed?.call();
          onFinish?.call();
          return false;
        }
    }
  }

  /// 请求列表中的权限 如果有一项拒绝就返回
  static Future<PermissionStatus> _requestPermission(
      List<Permission> permissionList) async {
    PermissionStatus currentPermissionStatus = PermissionStatus.granted;
    if (permissionList.isEmpty) {
      return currentPermissionStatus;
    }
    Map<Permission, PermissionStatus> result = await permissionList.request();
    result.forEach((key, status) {
      if (status.isDenied ||
          status.isPermanentlyDenied ||
          status.isRestricted) {
        currentPermissionStatus = status;
        return;
      }
    });
    return currentPermissionStatus;
  }

  static Future<bool> isAndroidAPIBelow33() async {
    final version = await androidSDKVersion();
    if (version == null) {
      return false;
    }
    return version < 33;
  }

  static Future<int?> androidSDKVersion() async {
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    if (!kIsWeb && Platform.isAndroid) {
      AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
      final version = androidInfo.version.sdkInt;
      return version;
    }
    return null;
  }
}
